import { useRef, useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom'
import * as uuid from 'uuid'
import HtmlTooltip from '../component/HtmlTooltip';
import { createIndexDB,IndexDB } from '../tools/indexDb'
import axios from '../../api/request'
import './video.css'
import Pcstyle from '../css/pc/video.module.css'
import Mstyle from '../css/mobile/video.module.css'
import { connect } from 'react-redux'
import { selectCounter } from '../store/models/counterSlice'



/**
 * @desc  注意节流防抖函数在react 函数组件更新时会重新创建  必须用hook创建函数保存状态
 * @param {*} fn 
 * @param {*} delay 
 * @returns 
 */
function useThrottle(fn,delay){
  const [start,setstart] = useState(0)
  return function() {
    // 注意此处this指向 函数调用者
    let context = this
    let args = arguments
    let now = new Date().getTime()
    if (now - start > delay){
      // fn需要绑定上层函数this  否则默认为window调用
      fn.apply(context,args)
      // 重置起始时间
      // start.current = new Date().getTime()
      setstart(new Date().getTime())
    }
  }
}

function useDidMountEffect(fn,inputs){
  const didMountRef = useRef(null)
  useEffect(() => {
    if (!didMountRef.current) fn()
    else didMountRef.current = true
  },inputs)
}

function usePreState(value){
  const preRef = useRef(null)
  useEffect(() => {
    preRef.current = value
  },[value])
  return preRef.current
}

function useUnmounted(fn,value){
  console.log('hooks',value);
  const [idx,setidx] = useState(value)
  useEffect(() => {
    setidx(value)
  },[value])
  return idx
}



const promise = createIndexDB('dataBase','userInfo','id',['uuid','suid','play_point'])


function VideoCom(props){

  let style = props.isMobile ? Mstyle:Pcstyle

  const [activeIdx,setactiveIdx] = useState(0)
  const idxRef = useRef(null)
  
  const videoRef = useRef(null)
  const liRef = useRef(null)
  const location = useLocation()
  const state = location.state
  const list = state.source.list
  
  useEffect(() => {
    document.title =`${state.title}  ` + state.source.directory
    let video = videoRef.current
    let firstSrc = list[activeIdx].path
    let lastInfoStr = localStorage.getItem('allLastInfo')
    if (lastInfoStr){
      let directory = state.source.directory
      let allLastInfo = JSON.parse(lastInfoStr)
      let index = allLastInfo.findIndex(i => i.directory === directory)
      if (index < 0) {
        video.src = firstSrc
      } else {
        let lastInfo = allLastInfo[index]
        if(list[lastInfo.activeIdx]) {
          video.src = list[lastInfo.activeIdx].path
          video.currentTime = lastInfo.currentTime
          setactiveIdx(lastInfo.activeIdx)
        }
      }
      
    } else {
      video.src = firstSrc
    }
    
    return () => {
      // console.log('页面卸载');
      // saveProcess(video.currentTime,'unmounted')
      saveInfo(video)
    }
  },[])

  
  async function getProcess(){
    const indexdb = await promise
    const db = new IndexDB(indexdb)
    let dbResult = await db.getAll('userInfo')
    let suid = list[idxRef.current].suid
    if (dbResult.length > 0 && suid) {
      let uid = dbResult[0].uuid
      const res = await axios({url:'/api/source/getVideoProcess',params:{uuid:uid,suid}})
      return res
    }
    return null
  }

  async function saveProcess(currentTime, type = ''){
    const indexdb = await promise
    const db = new IndexDB(indexdb)
    let dbResult = await db.getAll('userInfo')
    let idx = type === 'unmounted' ? idxRef.current:activeIdx
    let suid = list[idx].suid
    let indexRes = await db.action('indexGet','userInfo',suid,'suid')
    let uid = uuid.v4()
    if (dbResult?.length > 0) {
      uid = dbResult[0].uuid
      if(indexRes){
        indexRes.suid = suid
      }
    } else {
      db.action('add','userInfo',{uuid:uid,suid,play_point:currentTime})
    }
    const res = await axios({method:'post',url:'/api/source/saveProcess',data:{uuid:uid,suid,playTime:currentTime}})
    return res
  }


  // 方法:视频加载完成后播放
  async function videoPlay(video){
    // const res = await getProcess()
    video.load()
    // let once = false
    video.oncanplay = (e) => {
      // if (once) return false
      // if (res?.code === 200 && res.data.playTime !== 0){
      //   video.currentTime = res.data.play_point
      //   console.log(video.currentTime);
      // }
      // once = true
      let {clientWidth,clientHeight} = e.target
      // ================ 适配移动端 =================
      if (props.isMobile){
        if (clientHeight > clientWidth){
          console.log(clientWidth,clientHeight);
          video.className = style.verticalscreen
        } else {
          video.className = ''
        }
      }
      // ============================================
      video.play()
    }
  }



  // 切换视频
  const changeSrc = async (type,idx) => {
    let video = videoRef.current
    if (activeIdx !== idx && idx < list.length && idx >= 0){
      setactiveIdx(idx)
      // saveProcess(type === 'click' ? video.currentTime:0)  // 此处有axios同步请求 要放到修改idx之后 否则会导致按钮卡顿
      video.src = list[idx].path
    }
  }

  // 事件:短视频页面鼠标滚动切换视频
  const mousewheel = useThrottle((e) =>{
    if (state.title !== '短视频') return
    let nextIdx = e.deltaY < 0 ? activeIdx-1:activeIdx+1
    changeSrc('mousewheel',nextIdx)
  },500)

  useEffect(()=> {
    let video = videoRef.current
    idxRef.current = activeIdx
    // scrollEvent()
    videoPlay(video)
    // 离开页面保存播放进度
    return () => {
      video.pause()
    }
  },[activeIdx])

  
  // 行为:存储播放进度
  const saveInfo = async (video) => {
    // if (state.title === '短视频') return
    // 获取当前页面信息
    let currentInfo = {
      directory:state.source.directory,
      activeIdx:idxRef.current,
      currentTime: video.currentTime,
    }
    // 初始化allCurrentInfo
    let allCurrentInfo = []
    // 读取storage
    let lastInfoStr = localStorage.getItem('allLastInfo')
    if (lastInfoStr) {
      allCurrentInfo = JSON.parse(lastInfoStr)
    }
    // 之前保存过就修改  没有就添加
    let index = allCurrentInfo.findIndex(i => i.directory === currentInfo.directory)
    if (index > -1) {
      allCurrentInfo[index] = currentInfo
    } else {
      allCurrentInfo.push(currentInfo)
    }
    // 保存到storage
    // localStorage.setItem('allLastInfo',JSON.stringify(allCurrentInfo))
    // 只记住最后一次
    localStorage.setItem('allLastInfo',JSON.stringify([currentInfo]))
  }
  
  
  // 行为:播放列表滚动到可视区域
  const scrollEvent = () => {
    if(!props.isMobile){
      liRef.current && liRef.current.scrollIntoView({block:'center',behavior:'smooth'})
    }
  }


  return <div className={`${style.videopage} videopage` }>
    <h1 style={{width: state.title !== '短视频' ? 'var(--videoW)':'100%'}}>{list[activeIdx].name}</h1>
    <div className={`${style.container}`}>

      <div className={`${style.left}`}>
        <video  onWheel={mousewheel} onEnded={() => changeSrc('onend', activeIdx+1)} ref={videoRef}  controls ></video>
      </div>
      <div className={style.right} >
        <div className={style.right_title}>{state.title}: {state.source.directory}</div>
        <ul className={style.video_list}>
          {
            list.map((item,index) => <li ref={(current) => {
              if (index === activeIdx) liRef.current = current
            }} className={activeIdx === index ? style.active:''} onClick={() => changeSrc('click',index)} key={item.name}>
                <p><HtmlTooltip title={item.name} placement="top" disableInteractive ><span>{item.name}</span></HtmlTooltip></p>
            </li>)
          }
        </ul>
      </div>
    </div>
  </div>
}

const mapStateToProps = (state) => {
  const counter = selectCounter(state)
  return {
    ...counter
  }
}

export default connect(mapStateToProps)(VideoCom)